package com.qianjiangcloud.store.activity;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.modle.ChildModel;
import com.qianjiangcloud.store.modle.MainModuleList;
import com.qianjiangcloud.store.modle.MainModules;
import com.qianjiangcloud.store.util.DownLoadZip;
import com.qianjiangcloud.store.util.GoodsDisplayUtils;
import com.qianjiangcloud.store.util.GsonUtils;
import com.qianjiangcloud.store.util.MainFragmentAdsUtils;
import com.qianjiangcloud.store.util.MainModulesComparator;
import com.qianjiangcloud.store.util.NewsAdsUtils;
import com.qianjiangcloud.store.util.ObtainViewFromType;
import com.qianjiangcloud.store.util.SlidingGoodsUtils;
import com.qianjiangcloud.store.util.ZipExtractorTask.FileToString;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.libary.cache.FileSystem.FileSystem;
import com.qianjiangcloud.store.libary.cache.common.EnhanceRecyclerView;

/**
 * Created by caojian on 16/6/28.
 */
public class MainShopFragment extends BaseDoFragment implements SwipeRefreshLayout.OnRefreshListener {
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView.LayoutManager layoutManager;
    private EnhanceRecyclerView recyclerView;
    private ShopAdapter myAdapter = null;
    private MainModuleList mainModuleList;
    private List<MainModules> modulesList = new ArrayList<MainModules>();
    private List<MainModules> list = new ArrayList<MainModules>();
    private MainModules modules = new MainModules();

    private Boolean isRefreshing = false;
    String url;
    //滑动广告
    private static final int SLIDE_ADVERTISEMENT_TYPE = 1;
    //新闻公告栏
    private static final int NEWS_ADVERTISEMENT_TYPE = 3;
    //滑动商品
    private static final int SLIDE_GOOD_TYPE = 5;
    //商品展示
    private static final int SHOW_GOOD_TYPE = 4;
    //快捷入口
    private static final int SHORTCUT_ENTRANCE = 2;
    //异形-热门市场
    private static final int HOT_TYPE = 6;
    //异性-超实惠
    private static final int BENEFIT_TYPE = 7;
    //异性-主题馆
    private static final int THEME_TYPE = 8;
    //异形-特色好货
    private static final int FEATURE_TYPE = 9;
    //异形-品牌秀
    private static final int BRAND_TYPE = 10;

    private FileToString fileToString = null;
    int number = 0;
    private RelativeLayout Shear;

    private MainFragmentAdsUtils mainFragmentAdsUtils = null;
    private GoodsDisplayUtils showGoodsUtils = null;
    private NewsAdsUtils newsAdsUtils = null;
    private SlidingGoodsUtils slidingGoodsUtils = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mActionBar.setShowTitleBar(false);
        mActionBar.setShowHomeView(false);
        rootView = inflater.inflate(R.layout.fragment_shop_main, null);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_purple, android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(this);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView = (EnhanceRecyclerView) rootView.findViewById(R.id.mylist);
        recyclerView.setLayoutManager(layoutManager);
        //recyclerView.setHasFixedSize(true);
        recyclerView.setOnPauseListenerParams(ImageLoader.getInstance(), false, true);

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        myAdapter = new ShopAdapter();
        //recyclerView.setAdapter(myAdapter);
        Shear = (RelativeLayout) rootView.findViewById(R.id.shangcheng_ll);
        Shear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AgentActivity.intentForFragment(mActivity,
                        AgentActivity.FRAGMENT_GOODS_SEARCH));
            }
        });
        mainFragmentAdsUtils = new MainFragmentAdsUtils();
        showGoodsUtils = new GoodsDisplayUtils();
        newsAdsUtils = new NewsAdsUtils();
        slidingGoodsUtils = new SlidingGoodsUtils();
        //下载文件
        doDownLoadWork();
    }

    //下拉刷新
    @Override
    public void onRefresh() {
        modulesList.clear();
        myAdapter.notifyDataSetChanged();
        if (!isRefreshing) {
            doDownLoadWork();
        }
    }


    //首页商品adapter
    private class ShopAdapter extends RecyclerView.Adapter {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ChildModel childModel = new ChildModel();
            RecyclerView.ViewHolder viewHolder = null;
            String json = null;
            double weight = 0;
            String module_title = null;
            String module_title_icon = null;
            String module_title_color = null;
            //是否显示查看更多
            String isshow_sub_module = null;
            //是否显示标题栏
            String isshow_module_title = null;
            String module_icon = null;
            int column_num = 0;
            View view = null;
            view = ObtainViewFromType.getView(viewType, getActivity());
            switch (viewType) {
                case SLIDE_ADVERTISEMENT_TYPE:
                    viewHolder = new SlideAdversementViewHodel(view);
                    break;
                case NEWS_ADVERTISEMENT_TYPE:
                    viewHolder = new NewsAdversementViewHodel(view);
                    break;
                case SLIDE_GOOD_TYPE:
                    viewHolder = new SlideGoodViewHodel(view);
                    break;
                case SHOW_GOOD_TYPE:
                    viewHolder = new ShowGoodViewHodel(view);
                    break;
                case SHORTCUT_ENTRANCE:
                    viewHolder = new ShortCutViewHodel(view);
                    break;
                case BENEFIT_TYPE:
                    viewHolder = new BenefitViewHodel(view);
                    break;
                case THEME_TYPE:
                    viewHolder = new ThemeViewHodel(view);
                    break;
                case FEATURE_TYPE:
                    viewHolder = new FeatureViewhodel(view);
                    break;
                case BRAND_TYPE:
                    viewHolder = new BrandViewHodel(view);
                    break;
                case HOT_TYPE:
                    viewHolder = new HotViewHodel(view);
                    break;

            }
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ChildModel childModel = new ChildModel();
            View view = null;
            LinearLayout layout = null;
            int viewType = getItemViewType(position);
            layout = (LinearLayout) holder.itemView.findViewById(R.id.item_line);
            if (position == 0 && null != layout) {
                layout.setVisibility(View.GONE);
            } else if (null != layout) {
                layout.setVisibility(View.VISIBLE);
            }
            try {

                childModel.json = readFile(modulesList.get(position).module_data);
                if (null != modulesList.get(position).module_id && !TextUtils.isEmpty(modulesList.get(position).module_id)) {
                    childModel.module_id = modulesList.get(position).module_id;
                }
                if (null != modulesList.get(position).weight && !TextUtils.isEmpty(modulesList.get(position).weight)) {
                    childModel.weight = Double.parseDouble(modulesList.get(position).weight);
                }
                if (null != modulesList.get(position).module_title && !TextUtils.isEmpty(modulesList.get(position).module_title)) {
                    childModel.module_title = modulesList.get(position).module_title;
                }
                if (null != modulesList.get(position).column_num && !TextUtils.isEmpty(modulesList.get(position).column_num)) {
                    childModel.column_num = Integer.parseInt(modulesList.get(position).column_num);
                }
                if (null != modulesList.get(position).module_title_color && !TextUtils.isEmpty(modulesList.get(position).module_title_color)) {
                    childModel.module_title_color = modulesList.get(position).module_title_color;
                }
                if (null != modulesList.get(position).module_title_icon && !TextUtils.isEmpty(modulesList.get(position).module_title_icon)) {
                    childModel.module_title_icon = modulesList.get(position).module_title_icon;
                }
                if (null != modulesList.get(position).module_icon && !TextUtils.isEmpty(modulesList.get(position).module_icon)) {
                    childModel.module_icon = modulesList.get(position).module_icon;
                }
                if (null != modulesList.get(position).isshow_module_title && !TextUtils.isEmpty(modulesList.get(position).isshow_module_title)) {
                    childModel.isshow_module_title = modulesList.get(position).isshow_module_title;
                }
                if (null != modulesList.get(position).isshow_sub_module && !TextUtils.isEmpty(modulesList.get(position).isshow_sub_module)) {
                    childModel.isshow_sub_module = modulesList.get(position).isshow_sub_module;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            switch (viewType) {
                case SLIDE_ADVERTISEMENT_TYPE:
                    try {
                        mainFragmentAdsUtils.setUpView(childModel.module_id, getActivity(), childModel.json, (float) childModel.weight, holder.itemView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case NEWS_ADVERTISEMENT_TYPE:
                    try {
                        newsAdsUtils.setUpview(childModel.json, getActivity(), holder.itemView, childModel.module_icon);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case SLIDE_GOOD_TYPE:
                    try {
                        slidingGoodsUtils.setUpView(getActivity(), childModel.json, childModel.isshow_sub_module, childModel.isshow_module_title, childModel.module_title, childModel.module_title_color, childModel.module_title_icon, holder.itemView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case SHOW_GOOD_TYPE:

                        showGoodsUtils.setUpview(modulesList.get(position).submodule_index,childModel.json, getActivity(), holder.itemView, childModel.module_title, childModel.module_title_color, childModel.module_title_icon, childModel.isshow_module_title);
                    break;
                case SHORTCUT_ENTRANCE:
                    ObtainViewFromType.setDateShortcutView(childModel.module_id, holder.itemView, viewType, getActivity(), childModel.json, childModel.weight, childModel.module_title, childModel.module_title_icon, childModel.module_title_color, childModel.column_num, childModel.module_icon, childModel.isshow_module_title, childModel.isshow_sub_module);
                    break;
                case BENEFIT_TYPE:
                    ObtainViewFromType.setDateBenrfitView(childModel.module_id, holder.itemView, viewType, getActivity(), childModel.json, childModel.weight, childModel.module_title, childModel.module_title_icon, childModel.module_title_color, childModel.column_num, childModel.module_icon, childModel.isshow_module_title, childModel.isshow_sub_module);
                    break;
                case THEME_TYPE:
                    ObtainViewFromType.setDateThemeView(childModel.module_id, holder.itemView, viewType, getActivity(), childModel.json, childModel.weight, childModel.module_title, childModel.module_title_icon, childModel.module_title_color, childModel.column_num, childModel.module_icon, childModel.isshow_module_title, childModel.isshow_sub_module);
                    break;
                case FEATURE_TYPE:
                    ObtainViewFromType.setDateFeatureView(childModel.module_id, holder.itemView, viewType, getActivity(), childModel.json, childModel.weight, childModel.module_title, childModel.module_title_icon, childModel.module_title_color, childModel.column_num, childModel.module_icon, childModel.isshow_module_title, childModel.isshow_sub_module);
                    break;
                case BRAND_TYPE:
                    ObtainViewFromType.setDateBrandView(childModel.module_id, holder.itemView, viewType, getActivity(), childModel.json, childModel.weight, childModel.module_title, childModel.module_title_icon, childModel.module_title_color, childModel.column_num, childModel.module_icon, childModel.isshow_module_title, childModel.isshow_sub_module);
                    break;
                case HOT_TYPE:
                    ObtainViewFromType.setDateHotView(childModel.module_id, holder.itemView, viewType, getActivity(), childModel.json, childModel.weight, childModel.module_title, childModel.module_title_icon, childModel.module_title_color, childModel.column_num, childModel.module_icon, childModel.isshow_module_title, childModel.isshow_sub_module);
                    break;
            }
        }

        @Override
        public int getItemCount() {
            return modulesList.size();
        }

        @Override
        public int getItemViewType(int position) {
            return Integer.parseInt(modulesList.get(position).module_type);
        }
    }


    //滑动广告
    private class SlideAdversementViewHodel extends RecyclerView.ViewHolder {
        public SlideAdversementViewHodel(View itemView) {
            super(itemView);
        }
    }

    //新闻公告栏
    private class NewsAdversementViewHodel extends RecyclerView.ViewHolder {
        public NewsAdversementViewHodel(View itemView) {
            super(itemView);
        }
    }

    //滑动商品
    private class SlideGoodViewHodel extends RecyclerView.ViewHolder {
        public SlideGoodViewHodel(View itemView) {
            super(itemView);
        }
    }

    //商品展示
    private class ShowGoodViewHodel extends RecyclerView.ViewHolder {
        public ShowGoodViewHodel(View itemView) {
            super(itemView);
        }
    }

    //快捷入口
    private class ShortCutViewHodel extends RecyclerView.ViewHolder {

        public ShortCutViewHodel(View itemView) {
            super(itemView);
        }
    }

    //异形商品—超实惠
    private class BenefitViewHodel extends RecyclerView.ViewHolder {

        public BenefitViewHodel(View itemView) {
            super(itemView);
        }
    }

    //异形商品-主题馆
    private class ThemeViewHodel extends RecyclerView.ViewHolder {

        public ThemeViewHodel(View itemView) {
            super(itemView);
        }
    }

    //异形商品-特色好货
    private class FeatureViewhodel extends RecyclerView.ViewHolder {
        public FeatureViewhodel(View itemView) {
            super(itemView);
        }
    }

    //异形商品-品牌秀
    private class BrandViewHodel extends RecyclerView.ViewHolder {
        public BrandViewHodel(View itemView) {
            super(itemView);
        }
    }

    //异形商品-热门市场
    private class HotViewHodel extends RecyclerView.ViewHolder {
        public HotViewHodel(View itemView) {
            super(itemView);
        }
    }


    //下载文件
    private void doDownLoadWork() {
        isRefreshing = true;
        File zip = new File(String.valueOf(FileSystem.getCachesDir(getActivity(), true)));
        DownLoadZip task = new DownLoadZip(Run.MAIN_URL + "/openapi/home/all", zip.getAbsolutePath(), getActivity(), new FileToString() {
            @Override
            public void fileToString() {
                String main = null;
                JSONObject jsonObject = null;
                try {
                    main = readFile("main_modules.json");
                    jsonObject = new JSONObject(main);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (null != jsonObject) {
                    mainModuleList = GsonUtils.fromJson(jsonObject.optString("data"), MainModuleList.class);
                    list = mainModuleList.module;
                    for (int i = 0; i < list.size(); i++) {
                        try {
                            String json = readFile(list.get(i).module_data);
                            JSONObject object = new JSONObject(json);

                            if (list.get(i).module_type.equals("4")) {

                                JSONArray data = object.optJSONObject("data").optJSONArray("info");

                                int iii= data.length();


                                if (data.length() > 0) {

                                    for (int k = 0; k < Math.ceil(data.length() / 2.0); k++) {


                                        MainModules modulessss = (MainModules)list.get(i).clone();
                                        modulessss.submodule_index = k;
                                        modulesList.add(modulessss);
                                    }

                                }

                            } else {
                                // AbnormalShapeList abnormalShapeList = GsonUtils.fromJson(object.optString("data"), AbnormalShapeList.class);
                                // if(null!=abnormalShapeList&& null != abnormalShapeList.info && abnormalShapeList.info.size() > 0)
                                modulesList.add(list.get(i));
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                    if(modulesList.size()==0)
                    {
                        return;
                    }

                    Collections.sort(modulesList, new MainModulesComparator());
                    recyclerView.setAdapter(myAdapter);
                    isRefreshing = false;
                    swipeRefreshLayout.setRefreshing(isRefreshing);
                }
            }
        });
        task.execute();
    }

    //读文件
    public String readFile(String fileName) throws IOException {
        String res;
        File url = new File(FileSystem.getCachesDir(getActivity(), true) + File.separator + "all" + File.separator + fileName);
        if (!url.exists()) {
            return null;
        }

        File file = new File(url.getAbsolutePath());

        FileInputStream fis = new FileInputStream(file);

        int length = fis.available();

        byte[] buffer = new byte[length];
        fis.read(buffer);
        res = EncodingUtils.getString(buffer, "UTF-8");

        fis.close();
        return res;
    }

}
